<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item>
          <!--<el-input v-model="table" placeholder="表"></el-input>-->
          <Search :allOpts="formInline.allOpts" v-model="formInline.cOpts" @getChangeItem="search"></Search>
        </el-form-item>
        <!--<el-form-item>-->
        <!--<el-input v-model="condition" placeholder="条件"></el-input>-->
        <!--</el-form-item>-->

        <el-form-item>
          <el-button type="success" @click="addRow">添加行</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" :disabled="butStatus.selectNum" @click="rmRow">删除行</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <!--内容-->
    <el-card class="box-card" v-for="(row, index) in rows">
      <div slot="header" class="clearfix" style="line-height:36px">
        <el-checkbox style="float: left;margin-right:10px;" v-model="row.checked"
                     @change="cgRowChecked(row)"></el-checkbox>
        <span style="line-height: 36px;">{{row.rowkey}}</span>
        <!--<el-input style="float: left;width:150px" v-model="row.input" placeholder="请输入内容"></el-input>-->
        <el-button type="success" size="small"  style="float: right; margin-right:10px;"  @click="addColumns(row)">添加列 </el-button>
        <el-button type="danger" size="small"  style="float: right; margin-right:10px;" :disabled="row.butStu" @click="rmColumns(row)">删除列

        </el-button>
      </div>
      <div style="text-align: left;">
        <div class="cardc" v-for="(column,j) in row.columns">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <el-checkbox style="float: left;margin-right:10px" v-model="column.checked"
                           @change="cgColumnChecked(column,row)"></el-checkbox>
              <span style="line-height: 36px;">{{column.key}}</span>
              <!--<el-input style="float: left;width:150px" v-model="row.input" placeholder="请输入内容"></el-input>-->
              <el-button style="float: right;" type="warning" size="small" @click="updateColumn(column,row)">修改</el-button>
            </div>
            <div>
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
                v-model="column.val">
              </el-input>
            </div>
          </el-card>
        </div>
      </div>
    </el-card>
    <el-col style="text-align: center;padding: 20px 0 0 0;">
      <el-button type="text" @click="pushRoms">加载更多</el-button>
    </el-col>

    <!--编辑界面-->
    <el-dialog :title="formTitle" v-model="dialogFormVisible" size="tiny">
      <el-form :model="form" :rules="editFormRules" ref="form" :label-width="formLabelWidth">
        <!--选择-->
        <el-form-item label="行健" prop="rowkey">
          <el-input v-model="form.rowkey" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="列" prop="column">
          <Attrinput v-model="form.column" type="1"></Attrinput>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="resetForm">取 消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">{{btnEditText}}</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
  import util from '../../common/util'
  import Attrinput from '../../components/Attrinput.vue'
  import Search from '../../components/Search.vue'
  import dao from '../../common/dao'
  export default {
    components: {Search, Attrinput},
    data() {
      return {
        formLabelWidth: '120px',
        formTitle: '添加行',
        btnEditText: '确定',
        dialogFormVisible: false,
        editFormRules: {
          rowkey: [
            {required: true, message: '请输入行健', trigger: 'blur'}
          ],
          column: [
            {
              required: true, validator: (rule, value, callback) => {
              let column = this.form.column;
              if (column.length == 0) {
                callback(new Error('请添加列'));
              } else {
                let o = true;
                for (let item of column) {
                  if (item.key == '' || item.val == '') {
                    callback(new Error('请添加列1'));
                    o = false;
                    break;
                  }
                }
                if (o) callback();
              }
            }, trigger: 'blur'
            },
            {
              validator: (rule, value, callback) => {
                let column = this.form.column;
                column.map( (item,index) => {
                  let kv = item.key.split(':')
                  if (kv.length != 2) {
                    callback(new Error('请按“列簇:列 值”形式输入！'))
                    return false
                  } else if (kv.length == 2 && kv[0] == '') {
                    callback(new Error('请按“列簇:列 值”形式输入！'))
                    return false
                  } else {
                    callback()
                  }
                })
              }, trigger: 'blur'
            }
          ],
        },
        formInline: {
          allOpts: [{
            key: 'name_space',
            label: '命名空间',
            type: 'sel',
            selOption: [],
            val: ''
          }, {
            key: 'table_name',
            label: '表名',
            type: '',
            val: ''
          }, {
            key: 'rowkey',
            label: '行健',
            type: '',
            val: ''
          }, {
            key: 'columns',
            label: '列名',
            type: '',
            val: ''
          }],
          cOpts: [{
            key: 'name_space',
            label: '命名空间',
            type: 'sel',
            selOption: [],
            val: ''
          }, {
            key: 'table_name',
            label: '表名',
            type: 'sel',
            selOption: [],
            val: ''
          }],
          key: ""
        },
        rows: [],
        dbs: '',
        form: {
          rowkey: '',
          column: [],
        },
        condition: '',
        butStatus: {
          formInline: {},
          selectNum: true,
        }
      }
    },
    methods: {

      pageInit(){
        dao.listNameSpace({}).then(res => {
          if (!res.body || res.body.retCode != '200') {
            util.apiMsg(res);
            return false;
          }
          let arr = [];
          let results = res.body.results || [];
          results.map(item => {
            let obj = {
              label: item,
              value: item,
            };
            arr.push(obj);
          });
          this.formInline.allOpts[0].selOption = arr;
          this.formInline.cOpts[0].selOption = arr;
          this.formInline.cOpts[0].val = arr[0].value;
          this.name_space_opt = arr;
//          this.getTableData();
        });
      },
      getTableList(obj){
        dao.listTables(obj).then(res => {
          if (!res.body || res.body.retCode != '200') {
            util.apiMsg(res);
            return false;
          }
          let tableList = [];

          res.body.results || (res.body.results = [])
          res.body.results.map(re => {
            if (re.table_name != "" && typeof(re.table_name) != "undefined") {
              tableList.push({label: re.table_name, value: re.table_name});
            }
          });
          this.formInline.allOpts.map(item => {
            if (item.key == 'table_name') {
              item.selOption = tableList;
            }
          });
          this.formInline.cOpts.map(item => {
            if (item.key == 'table_name') {
              item.selOption = tableList;
              if (tableList.length > 0) {
                item.val = tableList[0].value;
              } else {
                item.val = "";
              }
            }
          });
        });
      },
      getByRowkey () { //加载更多

        let obj = {};
        this.formInline.cOpts.map(item => {
          obj[item.key] = item.val;
        });
        let botRow = JSON.parse(JSON.stringify(this.rows)).pop() || {};
        obj.bottom_rowkey = botRow.rowkey || "";
        return dao.getByRowkey(obj).then(res => {
          if (!res.body || res.body.retCode != '200') {
            util.apiMsg(res);
            return false;
          }
          let column = {
            checked: false,
            key: "",
            val: "",
          };
          let results = res.body.results || [];
          let newData = results.map(item => {
            let obj = {
              checked: false,
              butStu: true,
              rowkey: item.rowkey || '',
              columns: []
            };
            for (let key in item.columns) {
              obj.columns.push({
                checked: false,
                key: key,
                val: item.columns[key],
              })
            }
            return obj
          });
          return newData;
        })

      },
      getTableData(){
        this.getByRowkey().then(rows => {
          this.rows = rows || [];
        })
      },
      getPageParameters(){
        let obj = {};
        this.formInline.cOpts.map(item => {
          if (item.key == 'table_name' || item.key == 'name_space') obj[item.key] = item.val;
        });
        return obj
      },
      editSubmit () {
        this.$refs.form.validate((valid) => {
          if (!valid) return false;
          this.$confirm('此操作将添加行, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let obj = {
              rowkey: this.form.rowkey,
            };
            this.formInline.cOpts.map(item => {
              if (item.key == 'table_name' || item.key == 'name_space') obj[item.key] = item.val;
            });
            let colums = [];
            this.form.column.map(item => {
              colums.push({
                "column_name": item.key,
                "value": item.val
              });
            });
            obj.columns = colums;
            dao.addRowByRowkey(obj).then(res => {
              if (!res.body || res.body.retCode != '200') {
                util.apiMsg(res);
                return false;
              }
              this.$message({
                type: 'success',
                message: '添加行成功!'
              });
              this.dialogFormVisible = false;
              this.rows = [];
              this.getTableData()
            });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消添加行'
            });
          });

        })
      },
      addRow(){
        this.form = {
          rowkey: '',
          column: [],
        };
        this.dialogFormVisible = true;
      },
      addColumns (row) {

        this.form = {
          rowkey: row.rowkey,
          column: [],
        };
        this.dialogFormVisible = true;
      },
      search(object){
        let obj = {};
        this.formInline.key = object.key;
        this.formInline.cOpts.map(item => {
          if (item.key == 'name_space')
            obj['name_space'] = item.val;
        });
        this.rows = [];
        if (this.formInline.key == "name_space") {
          this.getTableList(obj);
        } else if (this.formInline.key == "table_name") {
          this.getTableData();
        } else {
          this.getTableData();
        }
      },
      cgRowChecked(){
        let stu = false;
        for (let item of this.rows) {
          if (item.checked == true) {
            this.butStatus.selectNum = false;
            stu = true;
            break;
          }
        }
        if (!stu) this.butStatus.selectNum = true;
      },
      cgColumnChecked(column, row){
        let stu = true;
        for (let item of row.columns) {
          if (item.checked == true) {
            row.butStu = false;
            stu = false;
            break;
          }
        }
        if (stu) row.butStu = true;
      },
      rmRow(){
        let rowkeys = [];
        this.rows.map(item => {
          if (item.checked == true) {
            rowkeys.push(item.rowkey);
          }
        });
        if (rowkeys.length < 1) {
          this.$message({
            type: 'warning',
            message: '无删除项'
          });
          return false;
        }
        this.$confirm('此操作将永久删除行, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let obj = this.getPageParameters();
          obj.rowkey = rowkeys;
          dao.deleteRowByRowkey(obj).then(res => {
            if (!res.body || res.body.retCode != '200') {
              util.apiMsg(res);
              return false;
            }
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.rows = [];
            this.getTableData()
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      rmColumns(row){
        let columns = [];
        let rowkey = row.rowkey;
        row.columns.map(item => {
          if (item.checked) {
            columns.push(item.key);
          }
        });
        if (columns.length < 1) {
          this.$message({
            type: 'warning',
            message: '无删除项'
          });
          return false;
        }
        this.$confirm('此操作将永久删除列, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let obj = this.getPageParameters();
          obj.columns = columns;
          obj.rowkey = rowkey;
          dao.deleteColumnByRowkey(obj).then(res => {
            if (!res.body || res.body.retCode != '200') {
              util.apiMsg(res);
              return false;
            }
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getTableData()
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      pushRoms(){

        this.getByRowkey().then(rows => {
          rows || (rows = []);
          rows.map(item => {
            this.rows.push(item);
          })
        });

      },
      updateColumn(column, row){
        this.$confirm('此操作将永久修改该列, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let obj = this.getPageParameters();
          obj.rowkey = row.rowkey;
          obj.column = column.key;
          obj.value = column.val;
          dao.updateColumnByRowkey(obj).then(res => {
            if (!res.body || res.body.retCode != '200') {
              util.apiMsg(res);
              return false;
            }
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
            this.getTableData()
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消修改'
          });
        });
      },
      resetForm () { //重置表单
        this.$refs.form.resetFields();
        this.dialogFormVisible = false
      }

    },
    mounted: function () {
      this.pageInit();
    }
  }
</script>

<style scoped>
  .box-card {
    margin-top: 20px;
  }

  .cardc {
    display: inline-block;
    width: 300px;
  }

  .cardc .box-card {
    /*float: left;*/
    line-height: 36px;
    margin-left: 10px;
  }

  /* .clear:after {
     content: ".";
     display: block;
     height: 0;
     clear: both;
     visibility: hidden
   }*/

</style>